package com.tutu.controller.backend;

import com.tutu.controller.CommonsController;
import com.tutu.controller.common.CommonController;
import com.tutu.entity.DeviceData;
import com.tutu.service.DeviceDataService;
import com.tutu.utils.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Excel导入管理
 * Created by 涂奕恒 on 2018/3/12.
 */
@Controller
@RequestMapping(value = "backend/excel")
public class ExcelController extends CommonController {

    // webApp路径
    private static final String webPath = (Objects.requireNonNull(ExcelController.class.getResource("/")).getPath().substring(0, Objects.requireNonNull(ExcelController.class.getResource("/")).getPath().indexOf("WEB-INF")));

    // 临时文件名
    private static final String tempName = "baseExcel.xlsx";

    // 临时文件路径,不需要修改
    private static final String tempFilePath = webPath + tempName;

    // 导出模版
    private static final String RECORD_TEMPLATE = webPath + "excelTemplate" + "/" + "baseExcel.xlsx";

    public static String FILENAME = "设备小时数据表.xlsx";

    @Autowired
    DeviceDataService deviceDataService;

    /**
     * 导出设备数据记录
     */
    @RequestMapping(value = {"/exportDeviceData"})
    public void exportDeviceData(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, String> map) throws Exception {
        String deviceName = "";

        for (List<Map<String, Object>> deviceList : CommonsController.baseDeviceList.values())
            for (Map<String, Object> deviceMap : deviceList)
                if (deviceMap.get("code").equals(map.get("deviceCode"))) {
                    deviceName = deviceMap.get("name") + "";

                    break;
                }

        switch (Integer.parseInt(map.get("type"))) {
            case 2011:
                FILENAME = "设备" + deviceName + "实时数据表.xlsx";
                break;
            case 2051:
                FILENAME = "设备" + deviceName + "分钟数据表.xlsx";
                break;
            case 2061:
                FILENAME = "设备" + deviceName + "小时数据表.xlsx";
                break;
            case 2031:
                FILENAME = "设备" + deviceName + "日均数据表.xlsx";
                break;
        }

        List<DeviceData> list = deviceDataService.productExcel(map);
        ExcelUtil.createExcel(RECORD_TEMPLATE, list, tempFilePath);
        download(request, response, tempFilePath, "(" + map.get("searchDate") + ")" + FILENAME);
    }

    /**
     * 文件下载
     */
    public static void download(HttpServletRequest request, HttpServletResponse response, String tempName, String exportName) throws Exception {
        // 解决文件名乱码问题
        if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) { // IE浏览器
            exportName = URLEncoder.encode(exportName, "UTF-8");
        } else { // 其他浏览器
            exportName = new String(exportName.getBytes(StandardCharsets.UTF_8), "ISO8859-1");
        }

        InputStream inStream;
        inStream = new FileInputStream(tempName);

        // 设置输出的格式
        response.setContentType("application/x-download");// 设置为下载application/x-download
        response.addHeader("content-type ", "application/x-msdownload");
        response.setContentType("application/octet-stream");

        // 设置输出的文件名
        response.setHeader("Content-Disposition", "attachment; filename=\"" + exportName + "\"");

        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        OutputStream outStream = response.getOutputStream();
        PrintStream out = new PrintStream(outStream);

        while ((len = inStream.read(b)) > 0) {
            out.write(b, 0, len);
            out.flush();
        }
        out.close();
        inStream.close();

        // 导出完成，删除文件
        File file = new File(tempName);
        file.deleteOnExit();
    }
}
